#!/usr/bin/python

"""Main script from which the simulation is run.

Deals with creation of the simulation object, reading the input file and
initialising the system.

Run using:
      i-pi input_file.xml

Where 'input_file.xml' should be replaced by the name of the xml input file from
which the system data will be read. For a description of how the input file
should be formatted, see the reference manual.

Functions:
   main: Runs the simulation.
"""

import sys
from ipi.engine import simulation
from ipi.inputs.simulation import InputSimulation
from ipi.utils.io.io_xml import *
from ipi.utils.messages import banner, help, verbosity

def main(file_name):
   """Runs the simulation.

   Will run automatically when the module is used as a script.
   """

   ifile = open(file_name,"r")
   xmlrestart = xml_parse_file(ifile) # Parses the file.
   ifile.close()

   simrestart = InputSimulation()
   # Checks the input and partitions it appropriately.
   simrestart.parse(xmlrestart.fields[0][1])
   # Here we must do this manually; from here on everything should be automated by the messages classes
   if simrestart.verbosity.fetch() != "quiet" :
      banner()
      print " # i-pi starting from input file: ", file_name
   if simrestart.verbosity.fetch() != "quiet" and simrestart.verbosity.fetch() != "low" :
      print " --- begin input file content --- "
      ifile = open(file_name,"r")
      for line in ifile.readlines():
         print line,
      ifile.close()
      print " ---  end input file content  --- "

   simul = simrestart.fetch() # Creates the appropriate simulation object.
   simul.run()

   del simul

#This is what is run if the file is run as a script.
if __name__ == '__main__':
   if (len(sys.argv) != 2):
      help()
   else:
      main(sys.argv[1])
